package com.jason.reflect;

import com.jason.reflect.bean.Person;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * 反射类的构造函数,创建类的对象
 * @Author: Jason
 * @Date: 16/4/7
 * @Time: 22:34
 */
public class ReflectTest02 {

    // 反射构造函数 public Person()
    @Test
    public void test1() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        Class clazz = Class.forName("com.jason.reflect.bean.Person");
        Constructor constructor = clazz.getConstructor(null);
        Person p = (Person) constructor.newInstance(null);
        System.out.println(p.name);

    }
    // 反射构造函数 public Person(String name)
    @Test
    public void test2() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Class.forName("com.jason.reflect.bean.Person");
        Constructor constructor = clazz.getConstructor(String.class);
        Person p = (Person) constructor.newInstance("xxxxx");
        System.out.println(p.name);

    }

    // 反射构造函数 public Person(String name, int password)
    @Test
    public void test3() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Class.forName("com.jason.reflect.bean.Person");
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Person p = (Person) constructor.newInstance("xxxxx", 3);
        System.out.println(p.name);

    }

    // 反射构造函数 private Person(List list)
    @Test
    public void test4() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Class.forName("com.jason.reflect.bean.Person");
        Constructor constructor = clazz.getDeclaredConstructor(List.class); // private
        constructor.setAccessible(true); // 暴力反射
        Person p = (Person) constructor.newInstance(new ArrayList());
        System.out.println(p.name);

    }

    // 创建对象的另外一种途径
    @Test
    public void test5() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class clazz = Class.forName("com.jason.reflect.bean.Person");
        Person p = (Person) clazz.newInstance();
        System.out.println(p);

    }

}
